package com.slkj.shilixiaoyuanapp.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created  on 2018-07-17
 * @author 唐开阔
 * @describe 显示当前时间的view
 */
public class TimeView extends android.support.v7.widget.AppCompatTextView {
    private TextView textView;
    private String timeString;
    Disposable mDisposable;
    //三个构造方法分别是代码构造，xml+style构造和xml构造
    public TimeView(Context context) {
        this(context,null);
    }
    public TimeView(Context context, AttributeSet attrs) {
        this(context,attrs,0);

    }
    public TimeView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.textView = this;
        updateClock();
        Init(context);
    }



    //初始化方法
    private void Init(Context context) {

        Observable.interval(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(aLong -> {
                    updateClock();
                })
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        mDisposable = disposable;
                    }
                })
                .subscribe();
    }

    private void updateClock() {
        //更新时间
        Date date = Calendar.getInstance().getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        String dateString = formatter.format(date);
        textView.setText(dateString);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mDisposable.dispose();
    }
}